<template>
  <div class="canvas-box" :style="getStyle.canvas">
    <vue-context-menu
      ref="menu"
      :contextMenuData="contextMenuData"
      @exportZip="exportZip"
      @changeName="changeName"
      @exportImage="exportImage"
    ></vue-context-menu>
    <div class="canvas" @click="removeChartActiveAndMoveActive" @mousemove="move" @mouseup="up">
      <div v-for="(canvas, canvasIndex) in canvasList" :key="canvasIndex" v-show="canvas.active">
        <chart
          v-for="(chart, index) in canvas.chartList"
          :key="index"
          :type="chart.type"
          :columns="chart.columns"
          :values="chart.values"
          :value="chart.value"
          :active="chart.active"
          :moveActive="chart.moveActive"
          :zindex="chart.zindex"
          :height="chart.height"
          :width="chart.width"
          :chartIndex="index"
          :axis="chart.axis"
          :way="chart.way"
          :darkMode="chart.darkMode"
          
          :canvasIndex="canvasIndex"
          :canvasStartX="canvasStartX"
          :canvasEndX="canvasEndX"
          :canvasStartY="canvasStartY"
          :canvasEndY="canvasEndY"
          
          :echarts="canvas.echarts"
          :title="chart.title"
          :titleLeft="chart.titleLeft"
          :titleColor="chart.titleColor"
          :fontsize="chart.fontsize"
          :positionX="positionX"
          :positionY="positionY"
          :theX="chart.theX"
          :theY="chart.theY"
          :clusterCount="chart.clusterCount"
          
          :xAxisShow="chart.xAxisShow"
          :xAxisName="chart.xAxisName"
          :xAxisNameLocation="chart.xAxisNameLocation"
          :xAxisNameColor="chart.xAxisNameColor"
          :xAxisOffset="chart.xAxisOffset"
          :xAxisFontSize="chart.xAxisFontSize"
          :xAxisPosition="chart.xAxisPosition"
          
          :yAxisShow="chart.yAxisShow"
          :yAxisName="chart.yAxisName"
          :yAxisNameLocation="chart.yAxisNameLocation"
          :yAxisNameColor="chart.yAxisNameColor"
          :yAxisOffset="chart.yAxisOffset"
          :yAxisFontSize="chart.yAxisFontSize"
          :yAxisPosition="chart.yAxisPosition"

          :legendType="chart.legendType"
          :legendShow="chart.legendShow"
          :legendLeft="chart.legendLeft"
          :legendTop="chart.legendTop"
          :legendWidth="chart.legendWidth"
          :legendHeight="chart.legendHeight"
          :legendOrient="chart.legendOrient"
          :legendColor="chart.legendColor"
          :legendFontSize="chart.legendFontSize"
          
          v-on:set-active="setChartActive"
          v-on:set-move-active="setChartMoveActive"
          v-on:set-resize-type="setResizeType"
        ></chart>
      </div>
    </div>
    <div class="page-box" :style="getStyle.foot">
      <div
        class="page"
        v-for="(page, index) in pageList"
        :key="index"
        :class="{'active': canvasList[index].active}"
        @contextmenu="showMenu(index)"
        @click="setCanvasActive(page.index)"
      >
        <img @click.stop="removePage(index)" class="close" src="@/assets/image/main/关闭.png" />
        <span>{{page.name}}</span>
      </div>
      <div class="add" @click="addPage">
        <img src="@/assets/image/main/添加.png" />
      </div>
    </div>
  </div>
</template>

<script>
import chart from "@/components/common/Chart.vue";
import JSZip from "jszip";
import { saveAs } from "file-saver";
import Utils from "@/Utils/Utils";
import domtoimage from "dom-to-image";

import $ from "jquery";
export default {
  components: {
    chart,
  },
  props: ["canvasSizeStatus"],
  watch: {
    canvasList() {
      this.$forceUpdate();
    },
    canvasSizeStatus() {
      setTimeout(()=>{
      let canvas = $(this.$el).find(".canvas");
      this.canvasStartX = canvas.position().left;
      
      this.canvasEndX = this.canvasStartX + canvas.width();

      let rate = this.canvasEndX - this.preCanvasEndX

      this.changeChartX(rate)

      this.preCanvasEndX = this.canvasEndX
      }, 500)

    },
  },
  data() {
    return {
      contextMenuData: {
        // the contextmenu name(@1.4.1 updated)
        menuName: "demo",
        // The coordinates of the display(菜单显示的位置)
        axis: {
          x: null,
          y: null,
        },
        // Menu options (菜单选项)
        menulists: [
          {
            fnHandler: "exportZip", // Binding events(绑定事件)
            icoName: "fa fa-home fa-fw", // icon (icon图标 )
            btnName: "导出画布数据", // The name of the menu option (菜单名称)
          },
          {
            fnHandler: "exportImage", // Binding events(绑定事件)
            icoName: "fa fa-home fa-fw", // icon (icon图标 )
            btnName: "导出画布图片", // The name of the menu option (菜单名称)
          },
          // {
          //   fnHandler: "changeName",
          //   icoName: "fa fa-home fa-fw",
          //   btnName: "修改画布名称",
          // },
        ],
      },

      positionX: 0,
      positionY: 0,
      pageList: [
        {
          index: 0,
          name: "第1页",
        },
      ],
      throttleResize: null,
      resizeStatus: false,
      resizeType: null,
      startPointX: 0,
      startPointY: 0,
      fixWidth: 0,
      fixHeight: 0,
      fixTheY: 0,
      fixTheX: 0,
      canvasStartX: 0,
      canvasEndX: 0,
      canvasStartY: 0,
      canvasEndY: 0,

      preCanvasEndX: 0,
    };
  },
  computed: {
    canvasList() {
      return this.$store.state.canvas.canvasList;
    },
    chartActive() {
      return this.$store.getters.getCanvasActive;
    },
    canvasWidth() {
      let canvas = $(this.$el).find(".canvas");

      return canvas.width();
    },
    getStyle(){
      return this.$store.state.theme.activeStyle
    }
  },
  created() {
    this.throttleResize = this.throttle(this.resize, 100);
  },
  mounted() {
    let canvas = $(this.$el).find(".canvas");
    this.canvasStartX = canvas.position().left;
    this.canvasEndX = this.canvasStartX + canvas.width();

    this.preCanvasEndX = this.canvasEndX

    this.canvasStartY = canvas.position().top;
    this.canvasEndY = this.canvasStartY + canvas.height();
  },
  methods: {
    changeChartX(rate){
      for(let i = 0; i < this.canvasList.length; i++){
        let canvas = this.canvasList[i]
        for(let j = 0; j < canvas.chartList.length; j++){
          let width = this.canvasList[i].chartList[j].width + rate
          if(width < 50) return 
          let data = {
            width,
            canvasIndex: i,
            chartIndex: j,
          }

          console.log(data, this.canvasList[i].chartList[j].width)
          this.$store.commit("setChartSizeOfIndex", data)
        }
      }
    },
    throttle(fn, delay = 1000) {
      let timer = null;
      let firstTime = true;

      return function (...args) {
        if (firstTime) {
          // 第一次加载
          fn.apply(this, args);
          return (firstTime = false);
        }
        if (timer) {
          // 定时器正在执行中，跳过
          return;
        }
        timer = setTimeout(() => {
          clearTimeout(timer);
          timer = null;
          fn.apply(this, args);
        }, delay);
      };
    },
    addPage() {
      let totalPage = this.pageList.length;
      let obj = {
        index: totalPage,
        name: `第${totalPage + 1}页`,
      };

      for (let i = 0; i < totalPage; i++) {
        let notIndex = true;
        for (let j = 0; j < totalPage; j++) {
          if (i == this.canvasList[j].index) {
            notIndex = false;
            break;
          }
        }

        if (notIndex == true) {
          let obj = {
            index: i,
            name: `第${i + 1}页`,
          };

          let canvasObj = {
            index: i,
            active: true,
            chartList: [],
          };

          // this.canvasList.push(canvasObj);
          this.$store.commit("addCanvas", canvasObj);
          this.pageList.push(obj);

          this.setCanvasActive(i);

          return;
        }
      }

      let canvasObj = {
        index: totalPage,
        active: true,
        chartList: [],
      };
      this.$store.commit("addCanvas", canvasObj);
      // this.canvasList.push(canvasObj);
      this.pageList.push(obj);

      this.setCanvasActive(totalPage);
    },
    setCanvasActive(index) {
      this.$store.commit("setCanvasActive", index);
    },
    setChartActive(activeIndex, chartIndex, val) {
      // this.canvasList[activeIndex].chartList[chartIndex].active = val;
      let data = {
        activeIndex,
        chartIndex,
        val,
      };
      this.$store.commit("setChartActive", data);
    },
    setChartMoveActive(activeIndex, chartIndex, val) {
      let data = {
        activeIndex,
        chartIndex,
        val,
      };

      this.$store.commit("setChartMoveActive", data);
    },
    setResizeType(data) {
      this.resizeStatus = true;
      this.resizeType = data.type;

      this.startPointX = data.startPointX;
      this.startPointY = data.startPointY;
      this.fixWidth = data.fixWidth;
      this.fixHeight = data.fixHeight;
      this.fixTheY = data.fixTheY;
      this.fixTheX = data.fixTheX;
    },
    getCanvasActive() {
      for (let canvas of this.canvasList) {
        if (canvas.active) {
          return canvas.index;
        }
      }

      return null;
    },
    removeChartActiveAndMoveActive() {
      this.$store.commit("removeChartActiveAndMoveActive");
    },
    removePage(index) {
      this.pageList.splice(index, 1);
      this.$store.commit("removeCanvas", index);

      this.$store.commit(
        "setCanvasActive",
        this.pageList[this.pageList.length - 1].index
      );
    },
    up() {
      this.resizeStatus = false;
    },
    move(e) {
      this.positionX = e.clientX;
      this.positionY = e.clientY;
      this.throttleResize();

      if (this.resizeStatus) {
        let x = this.positionX;
        let y = this.positionY;
        let width = null;
        let height = null;
        let theY = null;
        let theX = null;

        if (this.resizeType == "rightTop") {
          width = this.fixWidth + x - this.startPointX;
          height = this.fixHeight + this.startPointY - y;

          theY = this.fixTheY - (this.startPointY - y);
        } else if (this.resizeType == "leftTop") {
          width = this.fixWidth + this.startPointX - x;
          height = this.fixHeight + this.startPointY - y;

          theY = this.fixTheY - (this.startPointY - y);
          theX = this.fixTheX - (this.startPointX - x);
        } else if (this.resizeType == "leftBottom") {
          width = this.fixWidth + this.startPointX - x;
          height = this.fixHeight + y - this.startPointY;

          theX = this.fixTheX - (this.startPointX - x);
        } else if (this.resizeType == "rightBottom") {
          width = this.fixWidth + x - this.startPointX;
          height = this.fixHeight + y - this.startPointY;
        }

        let data = {
          width,
          height,
          theX,
          theY,
        };

        this.$store.commit("setChartSize", data);
      }
    },
    resize() {
      if (this.resizeStatus) {
        this.$store.commit("echartsResize");
      }
    },

    showMenu(index) {
      if (this.$store.getters.getCanvasActive != index) return;
      event.preventDefault();
      let height = $(this.$refs.menu.$el).height();
      var x = event.clientX;
      var y = event.clientY - height;

      // Get the current location
      this.contextMenuData.axis = {
        x,
        y,
      };
    },
    exportImage() {
      let canvas = $(this.$el).find(".canvas");
      // console.log(domtoimage)
      // return
      // domtoimage.bgcolor = "#333"
      let bgcolor = this.getStyle.canvas.backgroundColor
      domtoimage.toBlob(canvas[0], {bgcolor}).then(function (blob) {
        saveAs(blob, new Date().getTime() + ".jpg");
      });
    },
    async exportZip() {
      let zip = new JSZip();
      let index = this.$store.getters.getCanvasActive;
      let chartList = this.canvasList[index].chartList;
      for (let i = 0; i < chartList.length; i++) {
        let data = Utils.chartTransferArr(chartList[i]);

        await this.$axios.post("/download", data).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: res.msg,
            });
            zip.file(data.title + ".csv", res.data);
          } else this.$message.error(res.msg);
        });
      }

      zip.generateAsync({ type: "blob" }).then(function (blob) {
        saveAs(blob, new Date().getTime() + ".zip");
      });
    },
    changeName() {
      console.log("改变文件名字啦!");
    },
  },
};
</script>

<style scoped>
.active {
  background-color: rgb(255, 255, 255);
}

.canvas-box {
  display: flex;
  flex-direction: column;
}

.canvas-box .canvas {
  height: 96%;
  position: relative;
}

.canvas-box .page-box {
  display: flex;
  flex-direction: row;

  height: 4%;

  background-color: rgb(234, 234, 234);
  overflow-x: auto;
}

.page-box .page {
  width: 100px;
  flex-shrink: 0;
  padding: 5px;
  text-align: center;
  border-left: 1px solid black;
  user-select: none;
}

.page .close {
  height: 10px;
  width: 10px;
  display: block;
  float: right;

  visibility: hidden;
}

.page:hover .close {
  visibility: visible;
}

.page-box .page span {
  vertical-align: middle;
}

.page-box .add {
  height: 100%;
}

.page-box .add img {
  height: 100%;
}
</style>